package com.example.anjia03_3z.service.impl;


import com.example.anjia03_3z.exception.ServiceException;
import com.example.anjia03_3z.mapper.CategoryMapper;
import com.example.anjia03_3z.pojo.dto.CategoryAddNewDTO;
import com.example.anjia03_3z.pojo.dto.CategoryUpdateDTO;
import com.example.anjia03_3z.pojo.entity.Category;
import com.example.anjia03_3z.pojo.vo.CategoryListItemVO;
import com.example.anjia03_3z.pojo.vo.CategoryOptionsVO;
import com.example.anjia03_3z.pojo.vo.CategoryStandardVO;
import com.example.anjia03_3z.service.ICategoryService;
import com.example.anjia03_3z.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

@Service
@Slf4j
public class CategoryServiceImpl implements ICategoryService {

    @Autowired
    CategoryMapper mapper;

    @Value("${anjia.category.icon-path}")
    String dirPath;


    /**
     * 添加新的分类
     *
     * @param categoryAddNewDTO 获取的数据
     */
    public void addNew(CategoryAddNewDTO categoryAddNewDTO) {
        //判断名字是否已经存在
        int countByName = mapper.countByName(categoryAddNewDTO.getName());
        if (countByName >= 1) {
            throw new ServiceException("该分类已存在", ServiceCode.ERR_CONFLICT);
        }

        //创建category
        Category category = new Category();

        //将客户端数据赋值到category
        BeanUtils.copyProperties(categoryAddNewDTO, category);
        //赋值depth
        if (category.getParentId() == 0) {
            category.setDepth(1);
        } else {
            CategoryStandardVO standardVO = mapper.getStandardById(category.getParentId());
            if (standardVO == null) {
                throw new ServiceException("父级ID品类不存在", ServiceCode.ERR_NOT_FOUND);
            }
            //是否将父类更新为1
            if (standardVO.getIsParent() == 0) {
                Category parentCategory = new Category();
                standardVO.setIsParent(1);
                BeanUtils.copyProperties(standardVO, parentCategory);
                int row = mapper.update(parentCategory);
                if (row != 1) {
                    String message = "添加类别失败，服务器忙，请稍后尝试";
                    throw new ServiceException(message, ServiceCode.ERR_UPDATE);
                }
            }
            category.setDepth(standardVO.getDepth() + 1);
        }
        //赋值isParent
        category.setIsParent(0);

        //赋值时间
        category.setGmtCreate(LocalDateTime.now());
        category.setGmtModified(LocalDateTime.now());

        //添加category
        int row = mapper.insert(category);
        if (row != 1) {
            String message = "添加类别失败，服务器忙，请稍后尝试";
            throw new ServiceException( message,ServiceCode.ERR_INSERT);
        }
    }

    /**
     * @param parentId
     * @return
     */
    public List<CategoryListItemVO> listByParentId(Long parentId) {
        return mapper.listByParentId(parentId);
    }

    @Override
    public CategoryStandardVO getStandard(Long id) {
        CategoryStandardVO standardVO = mapper.getStandardById(id);


        if (standardVO == null) {
            String message = "数据已经不存在，请刷新";
            throw new ServiceException(message,ServiceCode.ERR_NOT_FOUND);
        }

        return standardVO;
    }

    @Override
    public void deleteById(Long id) {
//        判断需要删除的数据是否存在
        CategoryStandardVO standardVO = mapper.getStandardById(id);
        if (standardVO == null) {
            String message = "该数据不存在";
            throw new ServiceException(message,ServiceCode.ERR_NOT_FOUND);
        }

        String iconPath = standardVO.getIcon();

//        判断是否为父级
        if (standardVO.getIsParent() == 1) {
            String message = "该数据为还存在子级不能删除";
            throw new ServiceException(message,ServiceCode.ERR_CONFLICT);
        }

        int rows = mapper.deleteById(id);
        if (rows != 1) {
            String message = "删除数据失败，请稍后再试";
            throw new ServiceException(message,ServiceCode.ERR_DELETE);
        }


        rows = mapper.countByParentId(standardVO.getParentId());
        if (rows == 0 && standardVO.getParentId() != 0) {
            Category updateCategory = new Category();
            updateCategory.setId(standardVO.getParentId());
            updateCategory.setIsParent(0);
            rows = mapper.update(updateCategory);
            if (rows != 1) {
                String message = "删除数据失败，请稍后再试";
                throw new ServiceException(message,ServiceCode.ERR_UPDATE);
            }
        }

        //删除图片
        new File(dirPath + iconPath).delete();

    }

    public List<CategoryOptionsVO> getOptions() {
        List<CategoryOptionsVO> optionsVOS = new ArrayList<>();
        List<CategoryListItemVO> listItemVOS = mapper.list();
        Map<Long, CategoryOptionsVO> map = new HashMap<>();
        for (CategoryListItemVO listItemVO : listItemVOS) {
            if (listItemVO.getDepth() == 1) {
                CategoryOptionsVO optionsVO = new CategoryOptionsVO();
                optionsVO.setValue(listItemVO.getId());
                optionsVO.setLabel(listItemVO.getName());
                optionsVO.setChildren(setChildren(optionsVO, listItemVOS));
                optionsVOS.add(optionsVO);
            }
        }
        CategoryOptionsVO optionsVO = new CategoryOptionsVO();
        optionsVO.setValue(0L);
        optionsVO.setLabel("无父类");
        optionsVOS.add(optionsVO);
        return optionsVOS;
    }

    @Override
    public void updateById(Long id, CategoryUpdateDTO categoryUpdateDTO) {

        //判断数据是否存在
        CategoryStandardVO standardVO = mapper.getStandardById(id);
        if (standardVO == null) {
            throw new ServiceException("修改品类失败，数据库无该数据",ServiceCode.ERR_NOT_FOUND);
        }

        //判断名字是否冲突
        int row = mapper.countByNameAndNotId(id, standardVO.getName());
        if (row > 0) {
            throw new ServiceException( "修改相册失败，该名字已存在",ServiceCode.ERR_CONFLICT);
        }

        Category category = new Category();
        BeanUtils.copyProperties(categoryUpdateDTO, category);
        category.setId(id);
        mapper.update(category);

        new File(dirPath + categoryUpdateDTO.getIcon()).delete();
    }

    @Override
    public void setEnable(Long id) {
        updateEnable(id, 1);
    }

    @Override
    public void disable(Long id) {
        updateEnable(id, 0);
    }

    @Override
    public String uploadIcon(MultipartFile picFile) {
        String filename = picFile.getOriginalFilename();
        assert filename != null;
        String suffix = filename.substring(filename.lastIndexOf("."));
        filename = UUID.randomUUID() + suffix;
        String datePath = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
        datePath = "/category" + datePath;
        File dir = new File(dirPath + datePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        try {
            picFile.transferTo(new File(dir, filename));
        } catch (IOException e) {
            String message = "图片上传错误";
            throw new ServiceException(message,ServiceCode.ERR_UPDATE);
        }
        return datePath + filename;
    }

    @Override
    public void remove(String url) {
        new File(dirPath + url).delete();
    }

    private void updateEnable(Long id, int enable) {
        CategoryStandardVO standardById = mapper.getStandardById(id);
        //判断数据是否存在
        if (standardById == null) {
            String message = "该数据不存在";
            throw new ServiceException(message,ServiceCode.ERR_NOT_FOUND);
        }

        //判断是否启用状态冲突
        if (standardById.getEnable() == enable) {
            String message = ENABLE_STATE[enable] + "失败该数据已经" + ENABLE_STATE[enable] + "了";
            throw new ServiceException(message,ServiceCode.ERR_CONFLICT);
        }

        //更新启用状态
        Category category = new Category();
        category.setId(id);
        category.setEnable(enable);
        int rows = mapper.update(category);
        if (rows != 1) {
            String message = ENABLE_STATE[enable] + "类别失败，，服务器忙，请稍后再尝试！";
            throw new ServiceException(message,ServiceCode.ERR_UPDATE);
        }
    }

    private List<CategoryOptionsVO> setChildren(
            CategoryOptionsVO optionsVO,
            List<CategoryListItemVO> listItemVOS) {
        List<CategoryOptionsVO> children = new ArrayList<>();
        for (CategoryListItemVO listItemVO : listItemVOS) {
            if (listItemVO.getParentId().equals(optionsVO.getValue())) {
                CategoryOptionsVO vo = new CategoryOptionsVO();
                vo.setValue(listItemVO.getId());
                vo.setLabel(listItemVO.getName());
                if (listItemVO.getIsParent() == 1) {
                    vo.setChildren(setChildren(vo, listItemVOS));
                }
                children.add(vo);
            }
        }
        return children;
    }


}
